import { BrowserWindow, dialog, ipcMain } from "electron";
import { readFile, readdir,mkdir, access, constants, writeFile, rm } from "node:fs/promises";
import { resolve } from "node:path";

// 静态文件绝对路径
const staticPath = resolve(process.cwd(), './static')
access(staticPath, constants.F_OK).catch(err => mkdir(staticPath))

export let minWinMessage = null;

export class MainWinMessage {
  webContents;
  port;
  portListeners = []

  constructor(webContents) {
    this.webContents = webContents;

    ipcMain.on("port", this.initPort.bind(this));

    minWinMessage = this;

    this.handleIpc('dialog:openFile', dialogOpenFile)
    this.handleIpc('getDir', getDir)
    this.handleIpc('getFile', getFile)
    this.handleIpc('createFile', createFile)
    this.handleIpc('deleteFile', deleteFile)
  }

  initPort(event) {
    this.port = event.ports[0];
    // MessagePortMain 阻塞消息直到 .start() 方法被调用
    this.port.start();

    this.port.on("message", (event) => this.portListeners.forEach(fn => fn(event)));
  }

  sendIpcMessage(message: Message) {
    this.webContents.send("ipc-message", message);
  }

  onIpcMessage(callback: (event, message: Message) => unknown) {
    ipcMain.on("ipc-message", (event, message: Message) =>
      callback(event, message)
    );
  }
  postPortMessage(message: Message) {
    this.port.postMessage(message);
  }
  /**
   * @param event.data message
   */
  onPortMessage(callback: (event) => unknown) {
    this.portListeners.push(callback)
  }
  // ipcRenderer.invoke异步接收listener的返回值
  handleIpc(type, listener) {
    ipcMain.handle(type, listener);
  }
}

async function dialogOpenFile() {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    title: "选择文件",
  });
  if (!canceled) {
    return filePaths[0];
  }
}
// 获取目录
async function getDir(event, path) {
  let result = await readdir(resolve(staticPath, path), { recursive: true })

  if (Array.isArray(result)) {
    result = result.map(path => path.replace('\\', '/'))
  }

  return result
}
// 获取文件
async function getFile(event, path) {
  return readFile(resolve(staticPath, path))
}
// 创建文件
async function createFile(event, path, data) {
  const pathArr = path.split('/')
  let dirPath = pathArr.slice(0, pathArr.length - 1).join('/')
  dirPath = resolve(staticPath, dirPath)

  await access(dirPath, constants.F_OK).catch((err) => mkdir(dirPath, { recursive: true }));

  return writeFile(resolve(staticPath, path), data)
}
// 删除文件
async function deleteFile(event, path) {
  return rm(resolve(staticPath, path))
}

function setTile(event: any, message: Message) {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  if (message.type === "setTitle") {
    win.setTitle(message.data);

    // webContents.send("ipc-message", { type: "setTitle" })
  }
}
